<?php

namespace app\adminapi\controller;

use think\exception\ValidateException;
use think\Request;
use \app\common\business\Role as roleBs;
class Role  extends BaseApi
{

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $result = (new roleBs())->roleGetList();
        if(!$result){
            $this->ok();
        }
        $this->ok($result);

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //新增角色
        $params = input();
        try {
            validate(\app\adminapi\validate\Role::class)->check($params);
        }catch (ValidateException $e){
            $this->fail('新增角色失败');
        }

        try {
            $result = (new roleBs())->roleSave($params);
        }catch (\Exception $e){
            $this->fail($e->getMessage());
        }


        $this->ok($result);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if(empty($id)){
            $this->ok();
        }
        $userId = $this->request->userId;
        if($id !=$userId){
            $this->ok();
        }

        $result = (new roleBs())->getRoleById($id);
        if(!$result){
            $this->ok();
        }
        $this->ok($result);


    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $params = input();
        if(empty($id)){
            $this->fail('修改失败');
        }
        try {
            validate(\app\adminapi\validate\Role::class)->check($params);
        }catch (ValidateException $e){
            $this->fail('角色修改失败');
        }

        try {
            $result = (new roleBs())->roleUpdate($params,$id);
        }catch (\Exception $e){
            $this->fail($e->getMessage());
        }


        $this->ok($result);



    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if(empty($id)){
            $this->fail('请选择删除角色');
        }
        try{
            (new roleBs())->roleDelete($id);
        }catch(\Exception $e){
            $this->fail($e->getMessage());
        }
        $this->ok();




    }




}